<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.mentalPatient_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, getDetailByCard} from "@/api/ninebasic/specPersonnel/mentalPatient";
  import {mapGetters} from "vuex";
  import {validatenull,isvalidatemobile} from "@/util/validate";
  import {getPopulation} from "@/api/ninebasic/realpop/allPopulation";

  var DIC = {
          VAILD: [
            {
              label: "是",
              value: "2"
            },
            {
              label: "否",
              value: "1"
            }
          ]
        }
  export default {
    data() {
        //手机号校验非空
      const validatePhone = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };  
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 30,
          dialogWidth: 1250,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          excelBtn: true,
          dialogClickModal: false,
          column: [
            {
              label: "主键",
              prop: "id",
              type: "input",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              hide: true,
            },
            {
              label: "所属网格",
              prop: "gridId",
              type: "tree",
              span: 24,
              parent: true,
              display: true,
              dicMethod: "get",
              dicUrl: "/api/smart-system/dept/treeByPid",
              props: {
                label: "title"
              
              },
              checkStrictly: true,
              search: true,
              rules: [{
                required: true,
                message: "请输入所属网格",
                trigger: "click"
              }],
            },
            {
              label: "身份证号码",
              prop: "idCardNo",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                //validator: validateCardid,
                message: "请输入身份号码",
                trigger: "blur"
              }],
               blur: ({value}) => {
                 if(!validatenull(this.form.gridId)){
                    getDetailByCard(value,this.form.gridId).then(res => {
                    if(validatenull(res.data.data)) {
                        getPopulation(this.form.gridId,value).then(res => {
                          console.log(res.data);
                          if(!validatenull(res.data.data)) {
                                this.form.id = res.data.data.id;
                                this.form.name = res.data.data.name;
                                this.form.sex = res.data.data.sex;
                                this.form.birthday = res.data.data.birthday;
                                this.form.mobile = res.data.data.mobile;
                                this.form.liveAddrDetail = res.data.data.liveAddrDetail;
                                this.form.serviceSpace = res.data.data.serviceSpace; 
                          } else{
                            this.$message.error("身份证格式不正确或实有人口中不存在该人员，请先进行实有人员维护");
                          }
                      })
                       }else{
                      this.$message.error("该身份证号信息已存在");
                    }
                  })
                 }else{
                   this.$message.error("请先选择网格");
                 }
               }
            },
            {
              label: "姓名",
              prop: "name",
              type: "input",
              readonly: true,
              disabled:true,
              search: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }],
            },
            {
              label: "性别 ",
              prop: "sex",
              type: "select",
              readonly: true,
              disabled:true,
              dicUrl: "/api/smart-system/dict/dictionary?code=sex",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入性别 ",
                trigger: "blur"
              }],
            },
            {
              label: "出生日期",
              prop: "birthday",
              type: "date",
              readonly: true,
              disabled:true,
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              span: 8,
              rules: [{
                required: true,
                message: "请输入出生日期",
                trigger: "blur"
              }],
            },
            {
              label: "服务处所",
              prop: "serviceSpace",
              type: "input",
              readonly: true,
              disabled:true,
              span: 8,
              hide: true,
            },
            {
              label: "联系方式",
              prop: "mobile",
              type: "input",
              readonly: true,
              disabled:true,
              search: true,
              span: 8,
              rules: [{
                required: true,
                validator: validatePhone,
                //message: "请输入联系方式",
                trigger: "blur"
              }],
            },
            {
              label: "现住详址",
              prop: "liveAddrDetail",
              type: "input",
              hide: true,
              readonly: true,
              disabled:true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入现住详址",
                trigger: "blur"
              }],
            },
            {
              label: "家庭经济状况",
              prop: "familyFinancialStatus",
              type: "select",
              span: 8,
              dicUrl: "/api/smart-system/dict/dictionary?code=family_financial_status",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
            },
            {
              label: "是否纳入低保",
              prop: "isIncludedInTheLow",
              type: "radio",
              span: 8,
              dicData: DIC.VAILD,
              hide: true,
              rules: [{
                required: true,
                message: "请输入是否纳入低保",
                trigger: "blur"
              }],
            },
            {
              label: "监护人公民身份号码",
              prop: "guardianIdCard",
              type: "input",
              span: 8,
              hide: true,
            },
            {
              label: "监护人姓名",
              prop: "guardianName",
              type: "input",
              search: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入监护人姓名",
                trigger: "blur"
              }],
            },
            {
              label: "监护人联系方式",
              prop: "guardianContact",
              type: "input",
              span: 8,
              search: true,
              rules: [{
                required: true,
                message: "请输入监护人联系方式",
                trigger: "blur"
              }],
            },
            {
              label: "初次发病日期",
              prop: "firstOnsetDate",
              type: "date",
              span: 8,
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              hide: true,
            },
            {
              label: "目前诊断类型",
              prop: "diagnosisType",
              type: "select",
              span: 8,
              dicUrl: "/api/smart-system/dict/dictionary?code=diagnosisType",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入目前诊断类型",
                trigger: "blur"
              }],
            },
            {
              label: "有无肇事肇祸史",
              prop: "isTroublemaking",
              type: "radio",
              span: 8,
              dicData: [
              {
                label: "无",
                value: "2"
              },
              {
                label: "有",
                value: "1"
              }
            ],
              hide: true,
              rules: [{
                required: true,
                message: "请输入有无肇事肇祸史",
                trigger: "blur"
              }],
            },
            {
              label: "肇事肇祸次数",
              prop: "troublemakingAmount",
              type: "input",
              span: 8,
              hide: true,
            },
            {
              label: "上次肇事肇祸日期",
              prop: "lastTroublemakingDate",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              hide: true,
              span: 8,
            },
            {
              label: "目前危险性评估",
              prop: "dangerLevel",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=risk_assessment_grade",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入目前危险性评估",
                trigger: "blur"
              }],
            },
            {
              label: "治疗情况",
              prop: "treatmentSituation",
              type: "select",
              span: 8,
              dicUrl: "/api/smart-system/dict/dictionary?code=treatment",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入治疗情况",
                trigger: "blur"
              }],
            },
            {
              label: "治疗医院名称",
              prop: "treatmentHospitalName",
              type: "input",
              span: 8,
              hide: true,
            },
             {
              label: "接收康复训练机构名称",
              prop: "receiveTrainingInstitution",
              type: "input",
              span: 8,
              hide: true,
            },
            {
              label: "实施住院治疗原因",
              prop: "treatmentReason",
              type: "checkbox",
              span: 24,
              dicUrl: "/api/smart-system/dict/dictionary?code=reasons_for_hospitalization",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
            },
           
            {
              label: "参与管理人员",
              prop: "manager",
              type: "checkbox",
              span: 24,
              dicUrl: "/api/smart-system/dict/dictionary?code=participating_managers",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
            },
            {
              label: "帮扶情况",
              prop: "helpSituation",
              type: "checkbox",
              span: 24,
              dicUrl: "/api/smart-system/dict/dictionary?code=support_case",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
            },
            
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.mentalPatient_add, false),
          viewBtn: this.vaildData(this.permission.mentalPatient_view, false),
          delBtn: this.vaildData(this.permission.mentalPatient_delete, false),
          editBtn: this.vaildData(this.permission.mentalPatient_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        if(!validatenull(row.treatmentReason)){
        row.treatmentReason = row.treatmentReason.join(",");}
        if(!validatenull(row.manager)){
        row.manager = row.manager.join(",");}
        if(!validatenull(row.helpSituation)){
        row.helpSituation = row.helpSituation.join(",");}
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        
        console.log(row.treatmentReason);
       if(!validatenull(row.treatmentReason.join(","))){
        row.treatmentReason = row.treatmentReason.join(",");}
        if(!validatenull(row.manager.join(","))){
        row.manager = row.manager.join(",");}
        if(!validatenull(row.helpSituation.join(","))){
        row.helpSituation = row.helpSituation.join(",");}
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        //新增和修改页面，控制网格树加载职能选择末级，查询页面可以选择父级
        if (["edit", "add"].includes(type)) {
            const gridId = this.findObject(this.option.column,"gridId");
            gridId.parent = false;
           
        }
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
.el-form-item__content{
   margin-left: 160px ! important;
}
.el-form-item__label {
  width: 160px ! important;
}
</style>
